﻿using System;
using System.Collections.Generic;
using System.Linq;
using Google.GData.Client;
using TheOutfield.UmbExt.UniversalMediaPicker.Interfaces;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using Google.Picasa;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Picasa
{
    public class PicasaProvider : AbstractProvider
    {
        private readonly PicasaConfig _config;
        private IConfigControl _configControl;
        private ICreateControl _createControl;

        public PicasaProvider()
        { }

        public PicasaProvider(string config)
            : base(config)
        {
            _config = config.DeserializeJsonTo<PicasaConfig>();
        }

        public override string Alias
        {
            get { return "Picasa"; }
        }

        public override IConfigControl ConfigControl
        {
            get { return _configControl ?? (_configControl = new PicasaConfigControl(this, Config)); }
        }

        public override ICreateControl CreateControl
        {
            get { throw new NotImplementedException(); }
        }

        public override IList<MediaItem> GetMediaItems(string parentId)
        {
            var mediaItems = new List<MediaItem>();

            var requestSettings = new RequestSettings("Picasa", _config.Username, _config.Password);
            var picasaRequest = new PicasaRequest(requestSettings);

            if (parentId == "-1")
            {
                var albums = picasaRequest.GetAlbums();
                try
                {
                    mediaItems.AddRange(albums.Entries.Select(albumEntry => albumEntry.ToMediaItem()));
                }
                catch (GDataRequestException e)
                {
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, -1, "UMP Picasa exception: " + e.ResponseString);
                }
            }
            else
            {
                var photos = picasaRequest.GetPhotosInAlbum(parentId);
                mediaItems.AddRange(photos.Entries.Select(albumEntry => albumEntry.ToMediaItem()));
            }

            return mediaItems;
        }

        public override MediaItem GetMediaItemById(string id)
        {
            return PicasaHelper.GetMediaItemById(id, _config.Username, _config.Password);
        }
    }
}